<template>
  <canvas
    ref="worldElRef"
    id="threejs-container3"
    style="width: 100%; height: 100%"></canvas>
</template>

<script setup lang="ts">
import * as THREE from "three";
import ThreeJsWorld from "./ThreeJsWorld.ts";
import { onMounted, ref, onUnmounted } from "vue";
import * as CANNON from "cannon-es";

const worldElRef = ref();
const threeJsWorld = new ThreeJsWorld();
const raycaster = new THREE.Raycaster();

// 鼠标点击事件处理函数
const handleClick = (event) => {
  const mouse = new THREE.Vector2();
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  raycaster.setFromCamera(mouse, threeJsWorld.camera);
  const pos = new THREE.Vector3();
  pos.copy(raycaster.ray.direction);
  pos.add(raycaster.ray.origin);
  console.log("pos", pos);
  const compObj = threeJsWorld.addSphere(0.1, pos.x, pos.y, pos.z);
  let direction = new CANNON.Vec3(
    raycaster.ray.direction.x,
    0,
    raycaster.ray.direction.z
  );
  direction = direction.scale(5);
  compObj.objBody.applyLocalImpulse(
    // 冲力
    direction,
    new CANNON.Vec3(0, 0, 0)
  );
};

// 鼠标移动事件处理函数
const handleMouseMove = (event) => {
  // console.log("鼠标位置:", event.offsetX, event.offsetY);
};

// 按键按下事件处理函数
const handleKeyDown = (event) => {
  // console.log("按键被按下:", event.key);
};

onMounted(() => {
  threeJsWorld.initWorld({
    width: window.innerWidth,
    height: window.innerHeight,
    canvas: worldElRef.value,
  });
  threeJsWorld.setCameraPosition(20, 20, 20);
  threeJsWorld.addWorldGround();
  // threeJsWorld.addSphere(10, 0, 10, 0);
  // threeJsWorld.addSphere(10, 0, 110, 10);
  // threeJsWorld.addBox(10, 10, 10, 50, 100, 0);
  // threeJsWorld.addBox(10, 10, 10, 50, 100, 50);
  threeJsWorld.startWorld();

  const canvas = worldElRef.value;
  if (canvas) {
    canvas.addEventListener("click", handleClick);
    canvas.addEventListener("mousemove", handleMouseMove);

    // 键盘事件必须绑定到 window 或 document 上，因为 canvas 不聚焦
    window.addEventListener("keydown", handleKeyDown);
  }

  setInterval(() => {
    threeJsWorld.clearObj();
  }, 1000);
});

onUnmounted(() => {
  const canvas = worldElRef.value;
  if (canvas) {
    canvas.removeEventListener("click", handleClick);
    canvas.removeEventListener("mousemove", handleMouseMove);
    window.removeEventListener("keydown", handleKeyDown);
  }
});
</script>

<style scoped>
* {
  padding: 0px;
  margin: 0px;
}
#app {
  width: 100%;
  height: 100%;
}
</style>
